#include "manager.h"


QString manager::queryPopular() const{
    QFile file("../menu/菜品销量.txt");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        QString line;
        QString name="";
        while (!in.atEnd()) {
            line = in.readLine();

            QStringList parts = line.split(' ');
            double result;
            double start=0;
            result=parts[1].toDouble();

            if (result>start) {
                start=result;
                name=parts[0]+" 当前销量："+QString::number(start);
            }
        }
        return name;
        file.close();
        throw "未找到销量最高的菜品!";
    } else {
        throw "无法打开menu销量文件!";
    }
}
template<typename T>
void manager::sortInsert(QString name, QString type, T price) {
    QFile file("../menu/" + type + ".txt");
    if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
        // 文件打开失败处理逻辑
        throw "menu类型文件打开失败";
    }

    QString line;
    QString dishLine = name+ " " + QString::number(price);

    QStringList myQueue;
    int flag = 0;

    QTextStream in(&file);
    while (!in.atEnd()) {
        line = in.readLine();
        int result = line.section(" ", 1, 1).toDouble();

        if (flag == 0 && result >= price) {
            myQueue.append(dishLine);
            flag = 1;
        }
        myQueue.append(line);
    }

    if (flag == 0) {
        myQueue.append(dishLine);
    }

    file.resize(0); // 清空文件内容

    QTextStream out(&file);
    for (const QString &item : myQueue) {
        out << item << Qt::endl;
    }

    file.close();
    try{
        sortInsert(name,price);
    }catch(const QString &e){
        throw e;
    }
}
template<typename T>
void manager::sortInsert(QString name, T price) {
    QFile file("../menu/menu.txt");
    if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
        // 文件打开失败处理逻辑
        throw "menu文件打开失败";
    }

    QString line;
    QString dishLine = name+ " " + QString::number(price);

    QStringList myQueue;
    int flag = 0;

    QTextStream in(&file);
    while (!in.atEnd()) {
        line = in.readLine();
        int result = line.section(" ", 1, 1).toDouble();

        if (flag == 0 && result >= price) {
            myQueue.append(dishLine);
            flag = 1;
        }
        myQueue.append(line);
    }

    if (flag == 0) {
        myQueue.append(dishLine);
    }

    file.resize(0); // 清空文件内容

    QTextStream out(&file);
    for (const QString &item : myQueue) {
        out << item << Qt::endl;
    }

    file.close();
}

template void manager::sortInsert<double>(QString, QString, double);
